<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Models\BalanceLog;
use App\Models\SysDictData;
use Illuminate\Http\Request;

class BalanceController extends ApiBaseController
{
    public function getBalanceLog(Request $request)
    {
        $paginator = BalanceLog::filter($request->all())->with('user:id,username,nickname')->orderBy('id', 'desc')->paginate($this->pageSize);
        return success(page_format($paginator));
    }
    public function getBalanceType($type)
    {
        $dictData = SysDictData::where('dict_type', 'cz_balance_type')->get();
        $dictData = $dictData->toArray();
        $res = '';
        foreach ($dictData as $key => $value) {
            if ($value['dict_value'] == $type) {
                $res = $value['dict_label'];
                break;
            }
        }
        return $res;
    }
    public function exportData(Request $request)
    {
        // $field = "order_sn, product_name, face_value, mobile, price, created_at";
        $fileName = "资金记录导出[" . date('YmdHi') . "].csv";
        // 清空输出流，防止有别的信息
        ob_end_clean();
        // 打开一个输出流
        ob_start();
        // 设置header信息
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $fileName);
        header("Access-Control-Allow-Origin: *");

        // 打开文件流
        $fileHandle = fopen('php://output', 'w');
        //转码 防止乱码
        fwrite($fileHandle, chr(0xEF) . chr(0xBB) . chr(0xBF));
        $header_data = [
            '用户', '订单号', '类型', '金额', '变动前', '变动后', '说明', '创建时间'
        ];
        if (!empty($header_data)) {
            fputcsv($fileHandle, $header_data);
        }
        // 先把标题写进去
        //        fputcsv($fileHandle, $title);
        $params = $request->all();
        if (isset($request['ids'])) {
            BalanceLog::whereIn('id', $request['ids'])->dataFilter()->with('user:id,username,nickname')->orderBy('id', 'desc')->chunk(10000, function ($items) use ($fileHandle) {
                $arrs = $items->toArray();
                foreach ($arrs as $item) {
                    $newItem = [
                        $item['user']['nickname'],
                        $item['order_sn'],
                        $this->getBalanceType($item['type']),
                        $item['money'],
                        $item['bf_balance'],
                        $item['af_balance'],
                        $item['remark'],
                        $item['created_at'],
                    ];
                    fputcsv($fileHandle, $newItem);
                }
                //每2000条释放一次资源
                ob_flush();
                flush();
            });
        } else {
            BalanceLog::filter($params)->dataFilter()->with('user:id,username,nickname')->orderBy('id', 'desc')->chunk(10000, function ($items) use ($fileHandle) {
                $arrs = $items->toArray();
                foreach ($arrs as $item) {
                    $newItem = [
                        $item['user']['nickname'],
                        $item['order_sn'],
                        $this->getBalanceType($item['type']),
                        $item['money'],
                        $item['bf_balance'],
                        $item['af_balance'],
                        $item['remark'],
                        $item['created_at'],
                    ];
                    fputcsv($fileHandle, $newItem);
                }
                //每2000条释放一次资源
                ob_flush();
                flush();
            });
        }

        //释放资源
        ob_flush();
        flush();
        ob_end_clean();
    }
}
